<?php

namespace app\api\controller;

use adjust\SendS2sAdjust;
use app\admin\model\SmsConfig;
use app\api\model\AdjustLog;
use app\api\model\AppBase;
use app\api\model\AppBaseConfig;
use app\api\model\AppBaseUpdateLog;
use app\api\model\AppPayConfig;
use app\api\model\GuoXueLog;
use app\api\model\Order;
use app\api\model\User;
use app\api\model\UserEquipment;
use app\api\model\UserInfo;
use app\api\model\UserRegisterLog;
use app\api\model\UserSmsLog;
use app\common\controller\api\Base;
use facebook\SendFacebook;
use sms\Kmi;
use super\Random;
use think\Cache;
use think\Db;

class Index extends Base
{
    protected $noNeedLogin = [
        'login',
        'sendSms',
        'register',
        'resetPassword',
        'getAppConfig',
        'getAppBaseUpdateLog',
        'getUserInfoById',
        'getOrderById',
        'getDownloadUrl',
        'webOpen',
        'webDownload',
        'submitUserInfo',
    ];
    protected $checkKey = '123456';


    //登录
    public function login()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();

            $login = $this->auth->login($params, 2592000);
            if (!$login) {
                $this->error($this->auth->getError(), '', null, $this->auth->getErrorCode());
            }
            if (is_array($login)) {
//                $this->success('登录成功', null, $login);
                $this->success('login successful!', null, $login);
            }
            $user = $this->auth->getUserInfo($login);
            if ($user) {
                $data['id'] = $user['id'];

                $where = [
                    'app_base_id' => $user['app_base_id'],
                    'country_config_id' => $user['country_config_id'],
                ];
                $app_info = AppBaseConfig::where($where)->find();
                $data['sb'] = $app_info['sb'];
                if($user['id'] == 553986){
                    $data['sb'] = 1;
                }
                $data['username'] = $user['username'];
                $data['avatar'] = $user['avatar'];
                $data['token'] = $user['token'];
                $data['logintime'] = $user['logintime'];
                $data['loginip'] = $user['loginip'];
                $data['status'] = $user['status'];
                $data['current_status'] = $user['current_status'];
//                $this->success('登录成功', null, $data);
                $this->success('login successful!', null, $data);
            }
            $this->error('error!');
        }
    }

    //退出
    public function loginOut()
    {
        $out = $this->auth->logout($this->user['token']);
        if ($out) {
            $this->success('退出成功');
        }
    }

    //根据旧密码更新新密码
    public function resetPasswordByOldPassword()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (empty($params['old_password'])) {
//                $this->error('旧密码不能为空');
                $this->error('Please enter the original password!');
            }
            if (empty($params['new_password'])) {
//                $this->error('新密码不能为空');
                $this->error('Please enter a new password!');
            }
            $userInfo = User::where(['id' => $this->user['id']])->find();
            if (empty($userInfo)) {
//                $this->error('用户不存在');
                $this->error('error!');
            }
            $oldPassword = md5(md5($params['old_password']) . $userInfo['salt']);
            if ($oldPassword !== $userInfo['password']) {
//                $this->error('旧密码错误');
                $this->error('The original password is wrong!');
            }
            $newPassword = md5(md5($params['new_password']) . $userInfo['salt']);
            if ($oldPassword == $newPassword) {
//                $this->error('旧密码与新密码一致!');
                $this->error('The original password is the same as the new password!');
            }
            $userInfo['password'] = $newPassword;
            $res = $userInfo->save();
            if ($res) {
                $this->success('success!');
            }
//            $this->error('重置密码失败');
            $this->error('Network error, please try again!');
        }
    }

    public function submitUserInfo(){
        if ($this->request->isPost()) {

            $params = $this->request->post();
            if (empty($params["mobile"])){
                $this->error('携帯電話番号をご記入ください');
            }
            if (empty($params["username"])) {
                $this->error('お名前をご記入ください');
            }
            if (empty($params["birthday"])) {
                $this->error('生年月日をご記入ください。');
            }
            if (empty($params["sex"])) {
                $this->error('性別を選択。');
            }
            $params["birthday"] = $params["birthday"].":00:00";
            $age = calculateExactAge($params["birthday"]);
            if ($age <= 0) {
                $this->error('正しい誕生日を入力してください。');
            }
            $model = new UserInfo();
            $userInfo = $model->where([
                "mobile" => $params['mobile'],
                "username" => $params['username'],
                "is_del" => 0,
                "sex" => $params["sex"],
            ])->find();
            if ($userInfo) {
                $this->success("提出できました。オペレーターが連絡しますので、お待ちください。");
            }
            $ip = getRealClientIP();
            $data = [
                "mobile" => $params['mobile'],
                "username" => $params['username'],
                "age" => $age,
                "sex" => $params["sex"],
                "birthday" => $params["birthday"],
                'ip' => $ip,
            ];

            //获取客服组，分配
            $kefuGroupId = $this->getKefuGroupId();
            $data['status'] = 0;
            if (empty($kefuGroupId)) {
                //请先添加客服组以及对应客服
            }

            $kefuUserId = $this->getKefuUserId($kefuGroupId);
            if (!empty($kefuUserId)) {
                //请先添加客服组以及对应客服
                $data['customer_service_account_middle_id'] = $kefuUserId;
                $data['status'] = 1;
                $data['kefu_group_id'] = $kefuGroupId;
            }

            $ret = UserInfo::create($data);
            $id = $ret->getLastInsID();
            $data['id'] = $id;
            $dataT = [
                'ip' => $ip,
                'type' => 2,
            ];
            GuoXueLog::create($dataT);
            //pb
            $fbp = isset($params['fbp']) ?$params['fbp'] : "";
            $fbc = isset($params['fbc']) ?$params['fbc'] : "";
            request_post("https://api.ahgaesae005.com/api/index/jpSendFb", ['joinip'=>$ip, 'username' =>$params['mobile'],'fbp' => $fbp, 'fbc' => $fbc]);
            $this->success("提出できました。オペレーターが連絡しますので、お待ちください。", "", $data);
        }
    }

    protected function getKefuGroupId()
    {
        $key = "kefuGroup";
        $kefuGroupLen = Cache::store('redis')->llen($key);
        if (empty($kefuGroupLen)) return 0;
        $kefuGroupId = Cache::store('redis')->lpop($key);
        //获取客服，分配
        if ($kefuGroupId) {
            $kefuGroupInfo = Db::table('su_kefu_group')->where('status', '=', 1)->where('id', '=', $kefuGroupId)->find();
            if (empty($kefuGroupInfo)) {
                return $this->getKefuGroupId();
            }
            //判断当前客服组的分配量是都已经满了，没有满则放进分配队列，否则不放进分配队列中
            $startTime = date('Y-m-d 00:00:00');
            $endTime = date('Y-m-d 23:59:59');
            $kefuGroupCount = Db::table('su_user_info')->where('is_del', '=', 0)->where('create_time', 'between', [$startTime, $endTime])->where('kefu_group_id', '=', $kefuGroupId)->count();
            if ($kefuGroupCount+1 < $kefuGroupInfo['kefu_num']) {
                Cache::store('redis')->lpush($key, $kefuGroupId);
            }
            return $kefuGroupId;
        }
        return 0;
    }
    protected function getKefuUserId($kefuGroupId)
    {
        if (empty($kefuGroupId)) return 0;
        $key = "kefu_".$kefuGroupId."_user";
        $kefuUserLen = Cache::store('redis')->llen($key);
        if (empty($kefuUserLen)) {
            //分配给超量客服
            $kefuUserList = Db::table('su_kefu_user')->where('status', '=', 1)->where('is_excess_switch', '=', 1)->select()->toArray();
            $ids = array_column($kefuUserList, 'id');
            $key = array_rand($ids);
            return $ids[$key];
        };
        $kefuUserId = Cache::store('redis')->lpop($key);
        //获取客服，分配
        if ($kefuUserId) {
            $kefuUserInfo = Db::table('su_kefu_user')->where('status', '=', 1)->where('id', '=', $kefuUserId)->find();
            if (empty($kefuUserInfo)) {
                return $this->getKefuUserId($kefuGroupId);
            }
            $startTime = date('Y-m-d 00:00:00');
            $endTime = date('Y-m-d 23:59:59');
            $kefuUserCount = Db::table('su_user_info')->where('is_del', '=', 0)->where('create_time', 'between', [$startTime, $endTime])->where('customer_service_account_middle_id', '=', $kefuUserId)->count();
            if ($kefuUserCount+1 < $kefuUserInfo['customers_num']) {
                Cache::store('redis')->lpush($key, $kefuUserId);
            }
            return $kefuUserId;
        }
        return 0;
    }

    public function contactKefu()
    {
        if ($this->request->isPost()) {

            $params = $this->request->post();
            if (empty($params['id'])) {
                $this->error('客户id不能为空');
            }
            Db::table('su_user_info')->where('id', '=', $params['id'])->update(['is_check_kf_switch' => 1]);
            $user_info = Db::table('su_user_info')->where('id', '=', $params['id'])->find();
            if (empty($user_info['customer_service_account_middle_id'])){
                $this->error("未割り当てのサービス");
            }
            $kefu_account = Db::table('su_kefu_account')->where('kefu_user_id', '=', $user_info['customer_service_account_middle_id'])->where('status', '=', 1)->find();
            $kefu_user = Db::table('su_kefu_user')->where('id', '=', $user_info['customer_service_account_middle_id'])->where('status', '=', 1)->find();

            //获取分配客服的账号和客服链接
            $data = [
                'kefu_account' => $kefu_account['kefu_account'],
                'kefu_username' => $kefu_user['username'],
                'kefu_short_url' => $kefu_account['short_url'],
                'kefu_id' => $user_info['customer_service_account_middle_id'],
            ];
            $ip = getRealClientIP();
            $dataT = [
                'ip' => $ip,
                'type' => 3,
            ];
            GuoXueLog::create($dataT);
            $this->success("success", "", $data);


        }
    }

    //埋点接口
    public function buriedPoint()
    {
        $ip = getRealClientIP();
        $data = [
            'ip' => $ip,
        ];
        $params = $this->request->post();
        $type = isset($params['type']) ? $params['type'] : 1;
        $model = new GuoXueLog();
        $time =  date('Y-m-d');
        $endTime = date('Y-m-d 23:59:59');

        $where['create_time'] = ['between', [$time, $endTime]];
        $where['ip'] = $ip;
        $where['type'] = $type;
        $info = $model->where($where)->find();
        if (empty($info)) {
            $data['type'] = $type;
            GuoXueLog::create($data);
        }

        $this->success();
    }



}
